//
//  HonorRoolViewController.m
//  Cunli
//
//  Created by 湛亚 on 15/8/4.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "HonorRoolViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "HonorInfo.h"
#import "HonorListTableViewCell.h"
#import "HonorManagementViewController.h"
#import "MJRefresh.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface HonorRoolViewController ()<UITableViewDataSource,UITableViewDelegate>{
    
    NSMutableArray *honorArray;
    UITableView *honorTableView;
    int contentPage;
    NSMutableDictionary *zanDic;
}

@end

@implementation HonorRoolViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    if (self.orNavButton) {
        
        self.title=@"村务公开";
        [self createNavButton];
        honorTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-60) style:UITableViewStyleGrouped];
        
    }else{
        
        honorTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-140) style:UITableViewStyleGrouped];
    }
    honorTableView.dataSource=self;
    honorTableView.delegate=self;
    honorTableView.backgroundColor=[UIColor whiteColor];
    honorTableView.rowHeight=120;
    honorTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:honorTableView];
    
    honorArray=[[NSMutableArray alloc]init];
    zanDic=[[NSMutableDictionary alloc]init];
    contentPage=1;
    [self getHonorListWithPage:1 andBool:YES];
    
    [self addRefreshAttribute];
    
}

- (void)addRefreshAttribute
{
    __weak typeof(self) weakSelf = self;
    [honorTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:YES]; //刷新
    }];
    [honorTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
}

- (void)reloadDataToNew:(BOOL)new{
    
    if (new) {
        
        contentPage=1;
        [self getHonorListWithPage:1 andBool:YES];
    }else{
        contentPage=contentPage+1;
        [self getHonorListWithPage:contentPage andBool:NO];
    }
    
}

-(void)createNavButton{
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    //    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    rightBtn.frame = CGRectMake(0, 0, 65, 30);
    //    [rightBtn setTitle:@"发布" forState:UIControlStateNormal];
    //    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //    [rightBtn addTarget:self action:@selector(writeHonor) forControlEvents:UIControlEventTouchUpInside];
    //    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    //
    //    UIBarButtonItem *flexSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    //    flexSpacer.width = flexSpacer.width - 20;
    //    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flexSpacer, rightBarItem, nil]];
}

-(void)goBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)writeHonor{
    
    HonorManagementViewController *honorVC=[[HonorManagementViewController alloc]init];
    [self.navigationController pushViewController:honorVC animated:YES];
}

-(void)getHonorListWithPage:(int )page andBool:(BOOL )new{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",page] forKey:@"page"];
    [CheckParams setObject:@"10" forKey:@"pagesize"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"op_honorlist.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        NSDictionary *dataDic=[result objectForKey:@"data"];
        NSArray *honorlistArray=[dataDic objectForKey:@"honorlist"];
        
        if (honorlistArray.count==0) {
            if (!new) {
                
                MBProgressHUD *hud = [Config createHUD];
                hud.mode = MBProgressHUDModeCustomView;
                hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
                hud.labelText = @"没有更多数据";
                [hud hide:YES afterDelay:1];
                [honorTableView.legendHeader endRefreshing];
                [honorTableView.legendFooter endRefreshing];
                [honorTableView.legendFooter setState:MJRefreshFooterStateNoMoreData];
                return ;
            }else{
                
                [honorArray removeAllObjects];
                [honorTableView reloadData];
                [honorTableView.legendHeader endRefreshing];
                [honorTableView.legendFooter endRefreshing];
                [honorTableView.legendFooter setState:MJRefreshFooterStateNoMoreData];
                return ;
            }
        }
        
        if (new) {
            [honorArray removeAllObjects];
        }
        for (NSDictionary *dic in honorlistArray) {
            HonorInfo *honor=[[HonorInfo alloc]initWithDictionary:dic];
            [honorArray addObject:honor];
        }
        [honorTableView.legendHeader endRefreshing];
        [honorTableView.legendFooter endRefreshing];
        [honorTableView reloadData];
        
    }failureAction:^{
        
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return honorArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HonorInfo *honor=[honorArray objectAtIndex:indexPath.row];
    
    static NSString *identify = @"honorListCell";
    //HonorListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    
    HonorListTableViewCell *cell =(HonorListTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        
        cell = [[HonorListTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identify andHonor:honor];
    }
    cell.zanBtn.tag=indexPath.row;
    [cell.zanBtn addTarget:self action:@selector(addZan:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.orNavButton) {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //删除光荣榜
    HonorInfo *honor=[honorArray objectAtIndex:indexPath.row];
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:honor.itemid forKey:@"itemid"];
    [CheckParams setObject:@"3" forKey:@"type"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"del_article.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        NSString *str=[[result objectForKey:@"error"] objectForKey:@"text"];
        if (str) {
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"删除失败!";
            [hud hide:YES afterDelay:1];
            return ;
        }else{
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"删除成功!";
            [hud hide:YES afterDelay:1];
        }
        contentPage=1;
        [self getHonorListWithPage:1 andBool:YES];
        
    }failureAction:^{
        
    }];
    
}

-(void)addZan:(UIButton *)btn{
    
    HonorInfo *honor=[honorArray objectAtIndex:btn.tag];
    
    if ([zanDic objectForKey:[NSString stringWithFormat:@"%@",honor.itemid]]) {
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
        hud.labelText = @"您已点过赞";
        [hud hide:YES afterDelay:1];
        return;
    }
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:honor.itemid forKey:@"itemid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"honorpraise.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:@"honorpraise"]) {
            
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"点赞成功!";
            [hud hide:YES afterDelay:1];
            [zanDic setObject:@"1" forKey:[NSString stringWithFormat:@"%@",honor.itemid]];
            contentPage=1;
            [self getHonorListWithPage:1 andBool:YES];
        }else{
            
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"网络错误,点赞失败!";
            [hud hide:YES afterDelay:1];
        }
        
    }failureAction:^{
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}

@end
